/**
 * 漆水河 脚手架基础公开课
 * 2022/8/13 --- 2022/12/13
 * 有疑问可加QQ群: 809126489，后续会持续输出与大家一起成长
 */
package com.qishuihe.common.infrastructure.mail;

import com.qishuihe.common.infrastructure.mail.vo.MyMailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Component
public class MailSendHandler {


    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Autowired
    private MailProperties mailProperties;


   public boolean senSimpleMail(MyMailVO myMailVO){
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setText(myMailVO.getText());
        if(null!=myMailVO.getTo()){
            simpleMailMessage.setTo(myMailVO.getTo());
        }
       if(null!=myMailVO.getCc()){
            simpleMailMessage.setCc(myMailVO.getCc());
        }
        simpleMailMessage.setSubject(myMailVO.getSubject());
        simpleMailMessage.setFrom(mailProperties.getUsername());
        javaMailSender.send(simpleMailMessage);
     return true;
    }
    public boolean senMimeMail(MyMailVO myMailVO,Boolean isHaveMultipart)  {
        MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage);
        try {
            mimeMessageHelper.setText(myMailVO.getText(),true);
            if(null!=myMailVO.getTo()){
                mimeMessageHelper.setTo(myMailVO.getTo());
            }
            if(null!=myMailVO.getCc()){
                mimeMessageHelper.setCc(myMailVO.getCc());
            }
            mimeMessageHelper.setSubject(myMailVO.getSubject());

            mimeMessageHelper.setFrom(mailProperties.getUsername());
            if(isHaveMultipart){
                for(File file:myMailVO.getFiles()){
                    mimeMessageHelper.addAttachment(file.getName(),file);
                }
            }

        } catch (MessagingException e) {
            e.printStackTrace();
        }
        javaMailSender.send(mimeMailMessage);
        return true;
    }
}
